package com.kexio.auth.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import org.springframework.beans.factory.annotation.Autowired;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpInterface;
import com.kexio.auth.satoken.SaTokenStpInterfaceImpl;
import com.kexio.auth.interceptor.KexioSecurityEnhanceInterceptor;

/**
 * Sa-Token配置类
 * 
 * 负责Sa-Token框架的核心配置：
 * 1. 权限接口实现 (StpInterface)
 * 2. 路由拦截器配置
 * 3. 认证拦截规则
 * 4. 多租户支持配置
 * 
 * 与现有Kexio认证系统集成：
 * - 复用现有的UserAuthInfoProvider
 * - 保持现有的租户管理机制
 * - 集成现有的权限缓存体系
 * 
 * @author Kexio Team
 * @since 1.0.0 - Sa-Token集成版本
 */
@Configuration
@ConditionalOnProperty(prefix = "sa-token", name = "enabled", havingValue = "true", matchIfMissing = true)
public class SaTokenConfiguration implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(SaTokenConfiguration.class);
    
    @Autowired
    private KexioSecurityEnhanceInterceptor kexioSecurityEnhanceInterceptor;

    /**
     * Sa-Token权限验证接口实现
     * 
     * 集成现有的Kexio权限体系：
     * - 通过UserAuthInfoProvider获取用户权限
     * - 支持多租户权限隔离
     * - 利用Redis缓存提升性能
     * 
     * @return StpInterface实现
     */
    @Bean
    public StpInterface stpInterface(SaTokenStpInterfaceImpl impl) {
        logger.info("正在配置Sa-Token权限接口...");
        logger.info("Sa-Token权限接口配置完成: {}", impl.getIntegrationStatus());
        return impl;
    }

    /**
     * 注册Sa-Token原生拦截器 + Kexio安全增强拦截器
     * 
     * 设计理念：增量优化，而非重写
     * - Sa-Token原生拦截器：保持100%原生功能
     * - Kexio安全增强拦截器：在原生基础上添加增强功能
     * 
     * @param registry 拦截器注册表
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        logger.info("正在注册Sa-Token拦截器 + Kexio安全增强拦截器...");
        
        // 🎯 第1层：Sa-Token原生拦截器 (保持100%原生功能)
        registry.addInterceptor(new SaInterceptor())
            .addPathPatterns("/**")
            .excludePathPatterns(
                // 认证相关 - 必须排除的路径
                "/api/auth/login", "/api/auth/logout", "/api/auth/refresh",
                "/api/auth/register", "/api/auth/captcha",
                // 健康检查
                "/actuator/health", "/health",
                // 静态资源 
                "/favicon.ico", "/robots.txt",
                // API文档
                "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/doc.html",
                // 错误处理
                "/error", "/api/error"
            )
            .order(100); // 确保Sa-Token拦截器先执行
        
        // 🎯 第2层：Kexio安全增强拦截器 (增量优化)
        registry.addInterceptor(kexioSecurityEnhanceInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns(
                // 与Sa-Token保持相同的排除路径
                "/api/auth/login", "/api/auth/logout", "/api/auth/refresh",
                "/api/auth/register", "/api/auth/captcha",
                "/actuator/health", "/health",
                "/favicon.ico", "/robots.txt",
                "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs/**", "/doc.html",
                "/error", "/api/error"
            )
            .order(200); // 在Sa-Token拦截器之后执行
        
        logger.info("Sa-Token原生拦截器 + Kexio安全增强拦截器注册完成");
    }
}
